import logging
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)

class PerformanceEvaluator:
    def __init__(self, db_manager):
        """初始化绩效评估器"""
        self.db_manager = db_manager
        logger.info("绩效评估器初始化完成")
    
    def get_performance_data(self, days=30):
        """获取绩效数据"""
        try:
            capital_history = self.db_manager.get_capital_history(days)
            
            if not capital_history:
                logger.warning("没有资金历史数据")
                return []
            
            # 转换日期格式
            performance_data = []
            for record in capital_history:
                performance_data.append({
                    'date': str(record['RecordDate']),
                    'value': record['Amount']
                })
            
            logger.info(f"成功获取 {len(performance_data)} 条绩效数据")
            return performance_data
        except Exception as e:
            logger.error(f"获取绩效数据失败: {str(e)}")
            return []
    
    def calculate_performance_metrics(self, days=30):
        """计算绩效指标"""
        try:
            performance_data = self.get_performance_data(days)
            
            if not performance_data:
                return {
                    'total_return': 0,
                    'daily_return': 0,
                    'max_drawdown': 0,
                    'sharpe_ratio': 0
                }
            
            # 计算总收益率
            start_value = performance_data[0]['value']
            end_value = performance_data[-1]['value']
            total_return = (end_value - start_value) / start_value if start_value > 0 else 0
            
            # 计算日均收益率
            daily_return = total_return / len(performance_data) if len(performance_data) > 0 else 0
            
            # 计算最大回撤（简化版）
            peak = start_value
            max_drawdown = 0
            for data in performance_data:
                if data['value'] > peak:
                    peak = data['value']
                drawdown = (peak - data['value']) / peak
                if drawdown > max_drawdown:
                    max_drawdown = drawdown
            
            logger.info(f"绩效指标计算完成: 总收益={total_return:.2%}")
            return {
                'total_return': total_return,
                'daily_return': daily_return,
                'max_drawdown': max_drawdown,
                'sharpe_ratio': daily_return / max_drawdown if max_drawdown > 0 else 0
            }
        except Exception as e:
            logger.error(f"计算绩效指标失败: {str(e)}")
            return {
                'total_return': 0,
                'daily_return': 0,
                'max_drawdown': 0,
                'sharpe_ratio': 0
            }